/**
 * This class validates an input String as a number.
 * @author David Emole
 */
package com.spell;

public class NumValidator {
	
	public static void validateStringAsNumber(String str) throws NumberFormatException
	{
		//case: empty or null string
		if(str==null || str.isEmpty())
			throw new NumberFormatException("Empty");
		
		//case: large number
		if(str.length() > SpellConstants.INPUT_LIMIT)
			throw new NumberFormatException("enter a maximum of " + SpellConstants.INPUT_LIMIT + " characters");
		
		if(!isValidNumber(str))
			throw new NumberFormatException("Check your input");
	}
	
	/**
	 * Checks if the string is a valid whole number, comma separated, negative or decimal.
	 */
	public static boolean isValidNumber(String str) {
		/*
		 * Optional: Minus Sign
		 * Number: 	A series of digits 
		 * 			OR 
		 * 			A comma separated number [where the 1st part starts with a non-zero digit and contains at most 3 digits. 
		 * 			Subsequent parts should be a repetition of 'comma followed by 3 digits']  
		 * Optional: Decimal Point followed by one or more digits 
		 * Regex without escapes = ^-?((\d+)|([1-9]\d{0,2}(,\d{3})+)|(?=\.))(\.\d+)?$
		 */
		return str.matches("^-?((\\d+)|([1-9]\\d{0,2}(,\\d{3})+)|(?=\\.))(\\.\\d+)?$");
	}
}
